package log

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type Log struct {
	Logger *zap.SugaredLogger
}

func NewLogger(level string, logFileName string) *Log {
	logLevel := zapcore.InfoLevel
	switch strings.ToLower(strings.TrimSpace(level)) {
	case "debug":
		logLevel = zapcore.DebugLevel
	case "info":
		logLevel = zapcore.InfoLevel
	case "warn":
		logLevel = zapcore.WarnLevel
	case "error":
		logLevel = zapcore.ErrorLevel
	case "panic":
		logLevel = zapcore.PanicLevel
	case "fatal":
		logLevel = zapcore.FatalLevel
	}
	// encoder配置
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoder := zapcore.NewJSONEncoder(encoderConfig)
	// 日志文件配置和限制
	dir, _ := os.Executable()
	baseDir := filepath.Dir(dir)
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filepath.Join(baseDir, "log/", logFileName),
		MaxSize:    10,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	// log core
	core := zapcore.NewCore(encoder, zapcore.AddSync(lumberJackLogger), logLevel)
	// 添加调用情况
	logger := zap.New(core, zap.AddCaller())
	return &Log{
		Logger: logger.Sugar(),
	}
}

func (l *Log) Sync() error {
	return l.Logger.Sync()
}

func (l *Log) Debug(template string, args ...interface{}) {
	l.Logger.Debugf(template, args...)
}

func (l *Log) Info(template string, args ...interface{}) {
	l.Logger.Infof(template, args...)
}

func (l *Log) Warn(template string, args ...interface{}) {
	l.Logger.Warnf(template, args...)
}

func (l *Log) Error(template string, args ...interface{}) {
	l.Logger.Errorf(template, args...)
}

func (l *Log) Panic(template string, args ...interface{}) {
	l.Logger.Panicf(template, args...)
}

func (l *Log) Fatal(template string, args ...interface{}) {
	l.Logger.Fatalf(template, args...)
}
